package com.qidianit.mes.sys.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qidianit.mes.pojo.Result;
import com.qidianit.mes.pojo.Supplier;
import com.qidianit.mes.sys.mapper.SupplierMapper;
import com.qidianit.mes.sys.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ author: 周晓轩
 * @ company 起点编程
 * @ time: 2025/9/16 - 20:24
 * @ Description:
 */
@Service
public class SupplierServiceImpl implements SupplierService {
    @Autowired
    private SupplierMapper supplierMapper;

    @Override
    public Result<PageInfo<Supplier>> selectList(Supplier supplier, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Supplier> suppliers = supplierMapper.selectList(supplier);
        return Result.success(new PageInfo<>(suppliers));
    }

    @Override
    public Result<Supplier> selectByCode(String code) {
        return Result.success(supplierMapper.selectByCode(code));
    }

    @Override
    public Result<Supplier> addSupplier(Supplier supplier) {
        Result<Supplier> existResult = selectByCode(supplier.getCode());
        if (existResult.isSuccess() && existResult.getData() != null) {
            return Result.error("供应商编码已存在，新增失败");
        }
        return  supplierMapper.addSupplier(supplier) == 1?Result.success(supplier):Result.error("保存失败");
    }

    @Override
    public Result updateSupplierById(Supplier supplier) {
        Result<Supplier> existResult = selectByCode(supplier.getCode());
        if (existResult.isSuccess() && existResult.getData() != null) {
            // 存在相同编码的记录，且不是当前本人的记录
            if (!existResult.getData().getId().equals(supplier.getId())) {
                return Result.error("供应商编码已被占用，修改失败");
            }
        }
        return supplierMapper.updateSupplierById(supplier) == 1 ? Result.success():Result.error("编辑失败");
    }

    @Override
    public Result deleteById(Long id) {
        return supplierMapper.deleteById(id) == 1?Result.success():Result.error("删除失败");
    }

    @Override
    public Result batchDelete(Long[] ids) {
        return supplierMapper.batchDelete(ids) > 0?Result.success():Result.error("删除失败");
    }

}
